package org.datacoder.util

import org.codehaus.groovy.grails.plugins.DomainClassGrailsPlugin
import org.hibernate.SessionFactory
import org.hibernate.Session

class GeneralUtils {

    public static final String INTERVALS_PACKAGE = "org.datacoder.geocoding.datastructures.intervals"
    public static final String POINTS_PACKAGE = "org.datacoder.geocoding.datastructures.points"
    public static final String RECTANGLES_PACKAGE = "org.datacoder.geocoding.datastructures.rectangles"
    public static final String JURISDICTION_PACKAGE = "org.datacoder.geocoding.jurisdiction"

    public static void initializeClassList(String packageName, Class searchClass, List<Class> classList){
        String[] files = new File(Thread.currentThread().getContextClassLoader().getResource("../classes/${packageName.replace(".","/")}/").getFile()).list()
        Arrays.sort(files)
        for(int i = 0; i < files.length; i++){
            String theFile = files[i]
            if(theFile.endsWith(".class")){
                theFile = theFile.substring(0, theFile.length() - 6)
                Class clazz = Thread.currentThread().getContextClassLoader().loadClass("${packageName}.${theFile}")
                Class superclass = clazz.getSuperclass()
                if(superclass == searchClass){
                    classList.add(clazz)
                    continue
                }else{
                    Class[] interfaces = clazz.getInterfaces()
                    for(int j = 0; j < interfaces.length; j++){
                        if((interfaces[j] == searchClass)){
                            classList.add(clazz)
                            break
                        }
                    }
                }
            }
        }
    }

    public static void wipeReferences(SessionFactory sessionFactory){
        DomainClassGrailsPlugin.PROPERTY_INSTANCE_MAP.get().clear()
        Session session = sessionFactory.getCurrentSession()
        session.flush()
        session.clear()
    }

}

